#ifndef STREAM_READER_FFMPEG_H
#define STREAM_READER_FFMPEG_H

#include <iostream>
#include <string>

extern "C" {
/* Include ffmpeg header file */
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>

#include <libavutil/imgutils.h>
}
#include <opencv2/opencv.hpp>
#include <pthread.h>


class StreamReaderFFmpeg {
public:
  StreamReaderFFmpeg(std::string url, int camid);
  ~StreamReaderFFmpeg();
  int init();
  void release(); //just using for init failure.
  void Run();
  void Stop();    //just using for ending the Run().
  bool isStoped() { return this->stoped; }
  std::string GetUrl() { return this->url; }
  int GetCamid() { return this->camid; }
  cv::Mat GetCurFrame();

private:
  std::string url;
  int camid = -1;
  AVFormatContext *ifmt_ctx = NULL;
  AVDictionary* avdic = NULL;
  int video_index = -1;
  AVCodecContext * codec_ctx = NULL;
  AVCodec *codec = NULL;

  uint8_t *buffer = NULL;
  int numBytes = -1;
  AVFrame *rawframe = NULL;
  AVFrame *bgrframe = NULL;
  struct SwsContext *img_cvrt_ctx = NULL;

  pthread_t thd;
  static void* ThreadFunc(void* arg);

  bool stop = false;
  bool stoped = false;
  void Play();
  cv::Mat curFrame;
  pthread_mutex_t lock;
};

#endif //STREAM_READER_FFMPEG_H
